#!/usr/bin/python
#-*- coding: utf-8 -*-
import json
import redis
import yaml
import time
import sys
import datetime
import requests
from daemon import Daemon
import logging
from logging.handlers import TimedRotatingFileHandler,RotatingFileHandler
import os
import re
import base64
import hashlib
import threading
import Queue
import MySQLdb

reload(sys)
sys.setdefaultencoding('utf-8')

def lastCapturedIO(server_config,redis_cache,interval):
    #today last captured
    while True:
        try:
            today_index=time.strftime("%Y-%m-%d",time.localtime(time.time()))
            today_index_all=today_index+"_lastCaptured"
            today_count = redis_cache.scard(today_index_all)
            total_7=0
            for i in range(1,8):
                t_index=time.strftime("%Y-%m-%d",time.localtime(time.time()-i*86400))+"_lastCaptured"
                total_7 += redis_cache.scard(t_index)
            payload={"type":"hdFirstCity","to":122,"content":str(today_count)+","+str(total_7)}
            requests.post("http://"+server_config['mysql_web']['host']+":2121",data=payload,timeout=5)
            #logging.error("send:%s",str(today_count)+","+str(total_7))
        except Exception,e:
            logging.error("last captured error:%s",str(e))
        finally:
            time.sleep(interval)
    
def totalData(server_config,redis_cache,interval):
    while True:
        try:
            today_index=time.strftime("%Y-%m-%d",time.localtime(time.time()))
            key_total = today_index+"_total"
            key_plate = today_index+"_plate"
            payload={"type":"hdDayPort","to":122,"content":str(redis_cache.get(key_total))+","+str(redis_cache.scard(key_plate))}
            requests.post("http://"+server_config['mysql_web']['host']+":2121",data=payload,timeout=5)
        except Exception,e:
            logging.error("total error:%s",str(e))
        finally:
            time.sleep(interval)

def realData(server_config,redis_cache,interval):
    length=50
    mylist=[]
    tag=0
    last_total=0
    this_total=0
    while True:
        try:
            today_index=time.strftime("%Y-%m-%d",time.localtime(time.time()))+"_total"
            if tag==0:
                last_total=redis_cache.get(today_index)
                tag=1
                time.sleep(interval)    
            else:
                this_total=redis_cache.get(today_index)
                if len(mylist)==length:
                    del mylist[0]  
                if last_total is not None:
                    distance=int(this_total)-int(last_total)
                    #logging.error(distance)
                    time_str = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))
                    mylist.append([time_str,distance])
                    last_total=this_total
                    post_data={}
                    t_list=mylist
                    for li in t_list:
                        #print li
                        post_data[li[0]]=li[1]
                
                    payload={"type":"hdRealTimeCar","to":122,"content":json.dumps(post_data)}
                    requests.post("http://"+server_config['mysql_web']['host']+":2121",data=payload,timeout=5)
        except Exception,e:
            logging.error("realData error:%s",str(e))
        finally:
            time.sleep(interval)


def historyCount(server_config,interval):
    redis_count = redis.StrictRedis(unix_socket_path='/dev/shm/redis_counter.sock')
    db = MySQLdb.connect(host=server_config['mysql_web']['host'],
    port=server_config['mysql_web']['port'],
    user=server_config['mysql_web']['user'],
    passwd=server_config['mysql_web']['password'],
    db=server_config['mysql_web']['database'])
    db_cur = db.cursor()
    db_cur.execute("SET NAMES utf8")
    logging.info("start historyCount...")
    while True:
        try:
            now_time = int(time.time())
            if now_time % 3600 <= 60:
                if db is None:
                    db = MySQLdb.connect(host=server_config['mysql_web']['host'],
                    port=server_config['mysql_web']['port'],
                    user=server_config['mysql_web']['user'],
                    passwd=server_config['mysql_web']['password'],
                    db=server_config['mysql_web']['database'])
                    db_cur = db.cursor()
                    db_cur.execute("SET NAMES utf8")

                #获取昨天日期
                tn = datetime.datetime.now()+datetime.timedelta(days = -1)
                yestoday_str = tn.strftime('%Y%m%d')
                gczs = redis_count.get(yestoday_str+":gczs")
                cpzs = redis_count.pfcount(yestoday_str+":cpzs")
                cllxzs = redis_count.hgetall(yestoday_str+":cllxzs")
                gdcpzs = redis_count.hgetall(yestoday_str+":gdcpzs")
                sql="REPLACE INTO car_history_count (count_date, gczs, cpzs, cllxzs, gdcpzs , time_created) VALUES ("+str(yestoday_str)+", "+str(gczs)+", "+str(cpzs)+", '"+json.dumps(cllxzs)+"', '"+json.dumps(gdcpzs).replace("\\", "\\\\")+"', NOW()) "
                
                ok=db_cur.execute(sql)
                logging.info("historyCount:"+str(yestoday_str))
            time.sleep(60)
        except Exception,e:
            logging.error("historyCount error:%s",str(e))
                

class MyDaemon(Daemon):
    def __init__(self):
        self.name = 'board'
        self.map_place = {"浙":1,"闽":2,"粤":3,"京":4,"津":5,"冀":6,"晋":7,"蒙":8,"辽":9,"吉":10,"黑":11,"沪":12,"苏":13,"皖":14,"赣":15,"鲁":16,"豫":17,"鄂":18,"湘":19,"桂":20,"琼":21,"渝":22,"川":23,"贵":24,"云":25,"藏":26,"陕":27,"甘":28,"青":29,"宁":30,"新":31}
        Daemon.__init__(self, pidfile='/var/run/%s.pid' % (self.name.lower()), stderr='/tmp/board_err.log')

    def run(self):
        config_file = open(os.path.dirname(os.path.abspath(__file__)) + '/config.yaml')
        server_config = yaml.safe_load(config_file)
        config_file.close()

        logging.basicConfig(level=logging.INFO)
        handler = RotatingFileHandler('/var/log/%s.log' % self.name, maxBytes=134217728, backupCount=7)
        formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
        handler.setFormatter(formatter)
        logging.getLogger().addHandler(handler)

        r = redis.StrictRedis(unix_socket_path='/dev/shm/redis_pubsub.sock')
        redis_cache = redis.StrictRedis(host='127.0.0.1', port=6387, password='G&@uj*5VYc6n')
        pipe = redis_cache.pipeline()
        p = r.pubsub(ignore_subscribe_messages=True)
        topic = 'BIGDATA'
        p.subscribe(topic)
        #socket io last_captured
        t=threading.Thread(target=lastCapturedIO,args=(server_config,redis_cache,8))
        t.start()
        t=threading.Thread(target=totalData,args=(server_config,redis_cache,2))
        t.start()
        t=threading.Thread(target=realData,args=(server_config,redis_cache,3))
        t.start()
        t=threading.Thread(target=historyCount,args=(server_config,2))
        t.start()
        while True:
            img_url=''
            message = p.get_message()
            if message:
                #logging.error(message)
                data = message['data']
                json_data = json.loads(data)
                #logging.info(json_data)
                capture_time = json_data["capture_time"]
                plate_number = json_data["license_plate"]
                last_captured = json_data["last_captured"]
                date_index = capture_time.split(" ")[0]
                #当天总数
                total_index = date_index+'_total'
                pipe.incr(total_index)
                #当天车牌数
                plate_index=date_index+"_plate"
                pipe.sadd(plate_index,plate_number)
                #当前车牌生存时间为30*60
                pipe.setex("pl"+plate_number,180,1)
                #当天初次入区
                if int(last_captured)>30*86400:
                    lastCaptured_index = date_index+"_lastCaptured"
                    pipe.sadd(lastCaptured_index,plate_number)
                #当小时车牌数
                #hour = capture_time.split(" ")[1].split(":")[0]
                #hour_index = date_index+"_"+str(int(hour))
                #pipe.sadd(hour_index,plate_number)
                #split first char 
                first_char = plate_number.decode("utf8")[0:1].encode("utf8")     
                if self.map_place.has_key(first_char):
                    area_index = date_index+"_"+str(self.map_place[first_char])
                    pipe.sadd(area_index,plate_number)
                #execute
                pipe.execute()
                
                #将reids_count里的数据存入mysql
                
            else:
                print '无数据'
                time.sleep(1)


if __name__ == '__main__':
    daemon = MyDaemon()
    #daemon.run()
    # sys.exit()
    if len(sys.argv) == 2:
        if 'start' == sys.argv[1]:
            daemon.start()
        elif 'stop' == sys.argv[1]:
            daemon.stop()
        elif 'restart' == sys.argv[1]:
            daemon.restart()
        else:
            daemon.run()
            print "Unknown command"
            sys.exit(2)
            sys.exit(0)
    else:
        print "usage: %s start|stop|restart" % sys.argv[0]
        sys.exit(2)
